package com.braveman.im.ui.activity;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.content.Intent;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.braveman.im.R;
import com.braveman.im.bean.DataItemBean;
import com.braveman.im.bean.EditPersonInfoBean;
import com.braveman.im.bean.JsonNewBean;
import com.braveman.im.bean.PicUpdateBean;
import com.braveman.im.constant.Constants;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.thread.CompressPhotoThread;
import com.braveman.im.ui.weiget.ButtonItem;
import com.braveman.im.ui.weiget.CustomPopwindow;
import com.braveman.im.ui.weiget.DialogUtils;
import com.braveman.im.utils.GetJsonDataUtil;
import com.braveman.im.utils.PermissionUtils;
import com.braveman.im.utils.UtilsStyle;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ht.baselibs.core.EventCenter;
import com.ht.baselibs.core.EventCode;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.vondear.rxtools.RxBarTool;

import org.json.JSONArray;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by 昊昊 on 2017/10/11.
 */

/**
 * 我的详细信息
 */
public class DataItemActivity extends BaseActivity {
    private QMUIRadiusImageView activityDataHead;
    private ButtonItem activityDataNumber;
    private ButtonItem activityDataName;
    private ButtonItem activityDataSex;
    private ButtonItem activityDataPhone;
    private ButtonItem activityDataweixin;
    private ButtonItem activityDataQQ;
    private ButtonItem activityDataEmail;
    private ButtonItem activityDataBirthday;
    private ButtonItem activityDataPlace;
    private TextView activityDataSignature;
    private TextView activityDataExpectation;
    private ButtonItem activityDataCity;
    private ButtonItem activityDataEducation;
    private ButtonItem activityDataCompanyName;
    private ButtonItem activityDataDuty;
    private ButtonItem activityDataCompanyPhone;
    private ButtonItem activityDataIndustry;
    private ButtonItem activityDataAdress;
    private static final String TAKE_PHOTO_PATH = "ht/jkm/photo/HEADAV.jpg";
    private static final int REQUEST_CODE_TAKE_PHOTO = 1;
    private static final int REQUEST_CAMERA_CODE = 2;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 0;
    private static final int MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD = 1;
    private String picturePath;
    private String picturePathToURl;
    private DataItemBean dataItemBean;
    private static final int RESOUTDATEITEM = 200;
    private ButtonItem buttonItem;
    private int etType;
    private String picUrl;
    private String corpcityId;
    private String corpcityName;
    private String backgroupId;
    private String backgroupName;
    private String SexText;
    private String placeId;
    private String placeName;
    private ArrayList<JsonNewBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>>> options3Items = new ArrayList<>();
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private Thread thread;
    private boolean isLoaded = false;
    private String text;//所属行业
    private List<String> industry = new ArrayList<>();
    private List<String> backgrounds = new ArrayList<>();
    private List<String> Sexs = new ArrayList<>();
    private String[] industys = {"金融保险", "汽车交通", "房产服务", "医疗健康", "旅游", "游戏", "广告营销", "文化娱乐", "物流", "IT互联网"};
    private String[] background = {"小学", "初中", "高中", "大专", "大学", "研究生", "博士", "硕士", "教授", "学者"};
    private String[] Sex = {"男", "女"};
    private DatePickerDialog mDatePickerDialog;
    private int mEndYear;
    private int mEndMonth;
    private int mEndDay;
    private int mStartMonth;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("详细信息").setLeftBtnIcon(R.mipmap.back_black).setOnLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.finishActivity(DataItemActivity.this);
            }
        });
    }

    @Override
    protected int initContentView() {
        UtilsStyle.setStatusBarMode(this, true);
        RxBarTool.FlymeSetStatusBarLightMode(getWindow(), true);
        RxBarTool.MIUISetStatusBarLightMode(getWindow(), true);
        return R.layout.activity_data_item;
    }

    @Override
    protected void initChildView() {
        activityDataHead = findViewById(R.id.activity_data_head);
        activityDataNumber = (ButtonItem) findViewById(R.id.activity_data_number);
        activityDataName = (ButtonItem) findViewById(R.id.activity_data_name);
        activityDataSex = (ButtonItem) findViewById(R.id.activity_data_sex);
        activityDataPhone = (ButtonItem) findViewById(R.id.activity_data_phone);
        activityDataweixin = (ButtonItem) findViewById(R.id.activity_dataweixin);
        activityDataQQ = (ButtonItem) findViewById(R.id.activity_data_QQ);
        activityDataEmail = (ButtonItem) findViewById(R.id.activity_data_email);
        activityDataBirthday = (ButtonItem) findViewById(R.id.activity_data_birthday);
        activityDataPlace = (ButtonItem) findViewById(R.id.activity_data_place);
        activityDataSignature = (TextView) findViewById(R.id.activity_data_signature);
        activityDataExpectation = (TextView) findViewById(R.id.activity_data_expectation);
        activityDataCity = (ButtonItem) findViewById(R.id.activity_data_city);
        activityDataEducation = (ButtonItem) findViewById(R.id.activity_data_education);
        activityDataCompanyName = (ButtonItem) findViewById(R.id.activity_data_company_name);
        activityDataDuty = (ButtonItem) findViewById(R.id.activity_data_duty);
        activityDataCompanyPhone = (ButtonItem) findViewById(R.id.activity_data_company_phone);
        activityDataIndustry = (ButtonItem) findViewById(R.id.activity_data_industry);
        activityDataAdress = (ButtonItem) findViewById(R.id.activity_data_adress);
        activityDataHead.setCircle(false);
    }

    // TODO: 2017/11/7 解析省市区数据 
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        Toast.makeText(DataItemActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    Toast.makeText(DataItemActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;
                case MSG_LOAD_FAILED:
                    Toast.makeText(DataItemActivity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;
                case 200: //图片
                    int type = (int) msg.obj;
                    switch (type) {
                        case 0:
                            picturePathToURl = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                            Glide.with(DataItemActivity.this)//
                                    .load(Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH)//
                                    .into(activityDataHead);
                            doUpdatePic();
                            break;
                        case 1:
                            picturePathToURl = picturePath;
                            Glide.with(DataItemActivity.this)//
                                    .load(picturePath)
                                    .into(activityDataHead);
                            doUpdatePic();
                            break;
                    }
                    break;
            }
        }
    };

    // TODO: 2017/11/7 籍贯选择器
    private void ShowPlaceView(final ButtonItem buttonItem) {
        OptionsPickerView placeView = new OptionsPickerView.Builder(DataItemActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                placeName = options3Items.get(options1).get(options2).get(options3).name;
                buttonItem.tv_des.setText(placeName);
                placeId = options3Items.get(options1).get(options2).get(options3).id;
                doNetWork(placeId, 0, placeName, 0);
            }
        }).setTitleText("您的籍贯").build();
        placeView.setPicker(options1Items, options2Items, options3Items);
        placeView.show();
    }

    // TODO: 2017/11/7 来往城市选择器
    private void ShowPickerView(final ButtonItem buttonItem) {
        OptionsPickerView pickerView = new OptionsPickerView.Builder(DataItemActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                corpcityName = options3Items.get(options1).get(options2).get(options3).name;
                buttonItem.tv_des.setText(corpcityName);
                corpcityId = options3Items.get(options1).get(options2).get(options3).id;
                doNetWork(corpcityId, 0, corpcityName, 0);
            }
        }).setTitleText("来往城市")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20).build();
        pickerView.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pickerView.show();
    }


    // TODO: 2017/11/7 所属行业选择器
    private void ShowDutyView(final ButtonItem buttonItem) {
        OptionsPickerView pickerView = new OptionsPickerView.Builder(DataItemActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                text = industry.get(options1);
                buttonItem.tv_des.setText(text);
                doNetWork(null, options1 + 1, null, 1);
            }
        }).setTitleText("选择行业")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20).build();
        pickerView.setPicker(industry);
        pickerView.show();
    }

    // TODO: 2017/11/7 学历选择器
    private void ShowBackgroundView(final ButtonItem buttonItem) {
        OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(DataItemActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                backgroupId = backgrounds.get(options1);
                backgroupName = backgrounds.get(options1);
                buttonItem.tv_des.setText(backgroupName);
                doNetWork(backgroupId, options1 + 1, null, 2);
            }
        }).setTitleText("您的学历").build();
        optionsPickerView.setPicker(backgrounds);
        optionsPickerView.show();
    }

    // TODO: 2017/11/7 性别选择器
    private void ShowSexView(final ButtonItem buttonItem) {
        final OptionsPickerView SexView = new OptionsPickerView.Builder(DataItemActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                SexText = Sexs.get(options1);
                buttonItem.tv_des.setText(SexText);
                doNetWork(SexText, options1 + 1, null, 3);
            }
        }).setTitleText("请选择性别").build();
        SexView.setPicker(Sexs);
        SexView.show();
    }

    /**
     * 选择器的拓展
     *
     * @param adressId
     * @param count
     * @param adress
     * @param type
     */
    private void doNetWork(String adressId, int count, final String adress, int type) {
        EditPersonInfoBean editPersonInfoBean = new EditPersonInfoBean();
        switch (type) {
            case 0://来往城市
                editPersonInfoBean.intercourseCity = adress;
                editPersonInfoBean.interestCategoryId = adressId;
                break;
            case 1://所属行业
                editPersonInfoBean.corpIndustryName = text;
                break;
            case 2://学历程度
                editPersonInfoBean.educationId = backgroupId;
                editPersonInfoBean.educationName = backgroupName;
                break;
            case 3://性别
                editPersonInfoBean.gender = SexText;
                break;
            case 4://生日
                editPersonInfoBean.birth = adressId;
                break;
        }

        ApiManager.getApi().editPersonInfo(editPersonInfoBean).enqueue(new NetCallBack<EditPersonInfoBean>() {
            @Override
            protected void onSuccess(Call<EditPersonInfoBean> call, Response<EditPersonInfoBean> response) {
                if (response.body() != null) {
                    UIUtils.showToast("修改成功");
                }
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });


    }

    // TODO: 2017/11/7 Gson解析 
    public ArrayList<JsonNewBean> parseData(String result) {  //Gson 解析
        ArrayList<JsonNewBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonNewBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonNewBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    // TODO: 2017/11/7 解析数据
    private void initJsonData() {   //解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(DataItemActivity.this, "province_new.json");//获取assets目录下的json文件数据
        ArrayList<JsonNewBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<JsonNewBean.ChildBeanX.ChildBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < jsonBean.get(i).child.size(); c++) {//遍历该省份的所有城市
                JsonNewBean.ChildBeanX.ChildBean childBean = new JsonNewBean.ChildBeanX.ChildBean();
                childBean.name = jsonBean.get(i).child.get(c).name;
                childBean.id = jsonBean.get(i).child.get(c).id;
                CityList.add(childBean);//添加城市
                ArrayList<JsonNewBean.ChildBeanX.ChildBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).child.get(c).name == null
                        || jsonBean.get(i).child.get(c).child.size() == 0) {
                    City_AreaList.add(new JsonNewBean.ChildBeanX.ChildBean());
                } else {

                    for (int d = 0; d < jsonBean.get(i).child.get(c).child.size(); d++) {//该城市对应地区所有数据
                        JsonNewBean.ChildBeanX.ChildBean childBean1 = new JsonNewBean.ChildBeanX.ChildBean();
                        childBean1.name = jsonBean.get(i).child.get(c).child.get(d).name;
                        childBean1.id = jsonBean.get(i).child.get(c).child.get(d).id;
                        City_AreaList.add(childBean1);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);
            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.activity_data_name://真实姓名
                etType = 1;
                bundle.putInt("etType", etType);//EtType 1真实姓名  2 代表修改qq
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_dataweixin://微信
                etType = 2;
                bundle.putInt("etType", etType);
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_data_QQ://QQ
                etType = 3;
                bundle.putInt("etType", etType);
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_data_phone://手机号码:
                etType = 4;
                bundle.putInt("etType", etType);
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_data_email://email
                etType = 5;
                bundle.putInt("etType", etType);
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_data_birthday://生日:
                etType = 6;
                // TODO: 17/11/7 时间选择器
//                bundle.putInt("etType", etType);
//                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                doTimeSelect();
                break;
            case R.id.activity_data_signature://个人签名:
                etType = 7;
                bundle.putInt("etType", etType);
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_data_company_name://公司名称:
                etType = 8;
                bundle.putInt("etType", etType);
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_data_duty://职务
                etType = 9;
                bundle.putInt("etType", etType);
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_data_company_phone://公司电话:
                etType = 10;
                bundle.putInt("etType", etType);
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_data_adress://详细地址:
                etType = 11;
                bundle.putInt("etType", etType);
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_data_expectation://期望结识:
                etType = 12;
                bundle.putInt("etType", etType);
                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                break;
            case R.id.activity_data_sex://性别
//                etType = 13;
//                bundle.putInt("etType", etType);
//                ActivityUtils.startActivityForResult(this, EdTextActivity.class, bundle, RESOUTDATEITEM);
                ShowSexView(activityDataSex);
                break;
            case R.id.activity_data_city://选择城市:
                activityDataCity.tv_des.setText("");
                ShowPickerView(activityDataCity);
                break;
            case R.id.activity_data_industry://所属行业:
                ShowDutyView(activityDataIndustry);
                break;
            case R.id.activity_data_education://教育程度
                ShowBackgroundView(activityDataEducation);
                break;
            case R.id.activity_data_place://籍贯
                ShowPlaceView(activityDataPlace);
                break;
            case R.id.activity_data_head://头像
                try {
                    InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }
                break;
        }
    }

    private void doTimeSelect() {
//时间选择器
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        //正确设置方式 原因：注意事项有说明
        startDate.set(1960, 0, 1);
        endDate.set(2020, 11, 31);


        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String time = new SimpleDateFormat("yyyy-MM-dd").format(date);
                activityDataBirthday.tv_des.setText(time);
                doNetWork(time, 0, null, 5);
            }
        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择生日")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
                .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
//                .setLabel("年", "月", "日")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }


    @Override
    protected void initChildData() {
        for (String industy : industys) { //所属行业
            industry.add(industy);
        }

        for (String backgroud : background) { //学历背景
            backgrounds.add(backgroud);
        }
        for (String sex : Sex) {//性别选择
            Sexs.add(sex);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);//城市区

        ApiManager.getApi().getDataItem().enqueue(new NetCallBack<DataItemBean>() {
            @Override
            protected void onSuccess(Call<DataItemBean> call, Response<DataItemBean> response) {
                dataItemBean = response.body();
                activityDataName.tv_des.setText(dataItemBean.name);
                //String类型的图片地址通过Glide传给当前上下文，设置到ImagView的控件里面
                Glide.with(DataItemActivity.this).load(dataItemBean.avatar).into(activityDataHead);
                activityDataNumber.tv_des.setText(dataItemBean.sn);
                activityDataSex.tv_des.setText(dataItemBean.gender);
                activityDataPhone.tv_des.setText(dataItemBean.mobile);
                activityDataweixin.tv_des.setText(dataItemBean.wechatId);
                activityDataQQ.tv_des.setText(dataItemBean.qq);
                activityDataEmail.tv_des.setText(dataItemBean.email);
                activityDataBirthday.tv_des.setText(dataItemBean.birth);
                activityDataPlace.tv_des.setText(dataItemBean.birthplaceName);
                activityDataSignature.setText(dataItemBean.personalSignature);
                activityDataExpectation.setText(dataItemBean.lookForwardToMeet);
                activityDataCity.tv_des.setText(dataItemBean.residenceName);
                activityDataEducation.tv_des.setText(dataItemBean.educationName);
                activityDataCompanyName.tv_des.setText(dataItemBean.corpName);
                activityDataDuty.tv_des.setText(dataItemBean.corpJob);
                activityDataCompanyPhone.tv_des.setText(dataItemBean.corpPhone);
                activityDataIndustry.tv_des.setText(dataItemBean.corpIndustryName);
                activityDataAdress.tv_des.setText(dataItemBean.corpDetailedAddress);
            }
        });
    }

    @Override
    protected void setChildViewListener() {
        // img_head.setOnClickListener(this);
        activityDataHead.setOnClickListener(this);
        activityDataNumber.setOnClickListener(this);
        activityDataName.setOnClickListener(this);
        activityDataSex.setOnClickListener(this);
        activityDataPhone.setOnClickListener(this);
        activityDataweixin.setOnClickListener(this);
        activityDataQQ.setOnClickListener(this);
        activityDataEmail.setOnClickListener(this);
        activityDataBirthday.setOnClickListener(this);
        activityDataPlace.setOnClickListener(this);
        activityDataSignature.setOnClickListener(this);
        activityDataExpectation.setOnClickListener(this);
        activityDataCity.setOnClickListener(this);
        activityDataEducation.setOnClickListener(this);
        activityDataCompanyName.setOnClickListener(this);
        activityDataDuty.setOnClickListener(this);
        activityDataCompanyPhone.setOnClickListener(this);
        activityDataIndustry.setOnClickListener(this);
        activityDataAdress.setOnClickListener(this);
    }


    private void takePicture() {
        DialogUtils.createPopwindow(this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH);
                Uri data;
                // 判断版本大于等于7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
                    data = FileProvider.getUriForFile(DataItemActivity.this, "com.braveman.im.fileprovider", file);
                    // 给目标应用一个临时授权
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    data = Uri.fromFile(file);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, data);
                DataItemActivity.this.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);


            }
        }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {

                Intent i = new Intent(
                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, REQUEST_CAMERA_CODE);
            }
        }).showAtLocation(mTitleBarView, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 130);
    }


    private void doUpdatePic() {
        File file = new File(picturePathToURl);
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        showLoadingDialog();
        ApiManager.getApi().uploadPic("image", filePart).enqueue(new NetCallBack<List<PicUpdateBean>>() {
            @Override
            protected void onSuccess(Call<List<PicUpdateBean>> call, Response<List<PicUpdateBean>> response) {
                UIUtils.showToast("图片上传成功");
                PicUpdateBean picUpdateBean = response.body().get(0);
                EditPersonInfoBean editPersonInfoBean = new EditPersonInfoBean();
                editPersonInfoBean.avatar = picUpdateBean.url;
                ApiManager.getApi().editPersonInfo(editPersonInfoBean).enqueue(new NetCallBack<EditPersonInfoBean>() {
                    @Override
                    protected void onSuccess(Call<EditPersonInfoBean> call, Response<EditPersonInfoBean> response) {
                        if (response != null) {
                            EditPersonInfoBean editPersonInfoBean1 = response.body();
                            UIUtils.showToast("头像保存成功");
                            SharedPreferencesUtils.put(Constants.MINIMG, editPersonInfoBean1.avatar);
                            EventBus.getDefault().post(new EventCenter(EventCode.EVENT_CHANGE_AVATAR));
                        }
                    }

                    @Override
                    protected void hiddenProgress() {
                        hideLodingDialog();
                    }
                });
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePicture();
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case REQUEST_CODE_TAKE_PHOTO:
                    String filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                    new CompressPhotoThread(mHandler, filePath, 0).start();
                    break;
                //                 选择照片
                case REQUEST_CAMERA_CODE:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    new CompressPhotoThread(mHandler, picturePath, 1).start();
                    break;
                case RESOUTDATEITEM:
                    if (data != null) {
                        String date_name = data.getStringExtra("date_name");//找到控件，并且给控件赋名
                        switch (etType) {
                            case 1:
                                activityDataName.tv_des.setText(date_name);//把通过键值对取到的数值赋给控件
                                break;
                            case 2:
                                activityDataweixin.tv_des.setText(date_name);
                                break;
                            case 3:
                                activityDataQQ.tv_des.setText(date_name);
                                break;
                            case 4:
                                activityDataPhone.tv_des.setText(date_name);
                                break;
                            case 5:
                                activityDataEmail.tv_des.setText(date_name);
                                break;
                            case 6:
                                activityDataBirthday.tv_des.setText(date_name);
                                break;
                            case 7:
                                activityDataSignature.setText(date_name);
                                break;
                            case 8:
                                activityDataCompanyName.tv_des.setText(date_name);
                                break;
                            case 9:
                                activityDataDuty.tv_des.setText(date_name);
                                break;
                            case 10:
                                activityDataCompanyPhone.tv_des.setText(date_name);
                                break;
                            case 11:
                                activityDataAdress.tv_des.setText(date_name);
                                break;
                            case 12:
                                activityDataExpectation.setText(date_name);
                                break;
                            case 13:
                                activityDataSex.tv_des.setText(date_name);
                                break;
                        }
                    }
                    break;
            }
        }
    }


}
